<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键字">
          <el-input v-model="searchForm.keyword" placeholder="请输入标题关键字"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddAnnouncement">新增公告</el-button>
    </div>

    <!-- 公告表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="announcementId" label="公告ID" width="80"/>
      <el-table-column prop="title" label="标题" show-overflow-tooltip/>
      <el-table-column prop="content" label="内容" show-overflow-tooltip/>
      <el-table-column prop="userId" label="发布人ID" width="100"/>
      <el-table-column prop="createTime" label="创建时间" width="180"/>
      <el-table-column prop="updateTime" label="更新时间" width="180"/>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditAnnouncement(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteAnnouncement(scope.row.announcementId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
      <el-form :model="currentForm" :rules="rules" ref="announcementFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="currentForm.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="currentForm.content" :rows="10" placeholder="请输入公告内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {
  announcementDeleteOne,
  announcementInsertOne,
  announcementSelectPage,
  announcementUpdateOne
} from "@/api/announcement.js";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索条件
const searchForm = reactive({
  keyword: '',
});

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  announcementId: null,
  title: '',
  content: '',
  userId: 1, // 这里应该使用当前登录用户的ID
});
const announcementFormRef = ref(null);

// 验证规则
const rules = {
  title: [
    {required: true, message: '标题不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '标题长度在2到50个字符之间', trigger: 'blur'}
  ],
  content: [
    {required: true, message: '内容不能为空', trigger: 'blur'},
    {min: 10, message: '内容长度不能少于10个字符', trigger: 'blur'}
  ],
};

// 获取公告列表
const fetchAnnouncements = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      title: searchForm.keyword,
    };
    if (!params.keyword) {
      delete params.keyword;
    }
    const response = await announcementSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取公告列表失败');
  }
};

// 新增公告
const handleAddAnnouncement = () => {
  dialogTitle.value = '新增公告';
  dialogVisible.value = true;
  resetForm();
};

// 编辑公告
const handleEditAnnouncement = (row) => {
  dialogTitle.value = '编辑公告';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
};

// 删除公告
const handleDeleteAnnouncement = (announcementId) => {
  ElMessageBox.confirm('确认删除该公告?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await announcementDeleteOne(announcementId);
      ElMessage.success('删除成功');
      await fetchAnnouncements();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存公告（新增/编辑）
const handleSubmit = () => {
  announcementFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.announcementId) {
          // 编辑
          await announcementUpdateOne(currentForm);
        } else {
          // 新增
          await announcementInsertOne(currentForm)
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchAnnouncements();
      } catch (error) {
        ElMessage.error('保存失败');
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchAnnouncements();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchAnnouncements();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchAnnouncements();
};

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1;
  searchForm.keyword = '';
  fetchAnnouncements();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    announcementId: null,
    title: '',
    content: '',
    userId: 1, // 这里应该使用当前登录用户的ID
  });
  announcementFormRef.value?.clearValidate();
};

// 初始化数据
onMounted(() => {
  fetchAnnouncements();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
